<?php
namespace app\before\controller;

class User extends Base
{
    private $tn = 'user';

    public function index()
    {
        if (isset($this->get['page']) && isset($this->get['limit'])) {
            $where = [];
            //城市用户
            $where['from_city'] = ['in',$this->admin_area];
            if(isset($this->get['id'])){
                $where['id'] = $this->get['id'];
            }
            //注册方式
            if(isset($this->get['register_type'])){
                $where['register_type'] = $this->get['register_type'];
            }
            //注册时间
            if(isset($this->get['register_time'])){
                $where['register_time'] = [['egt',strtotime($this->get['register_time'])],['lt',strtotime($this->get['register_time'].'+1 day')]];
            }
            if(isset($this->get['keywords'])){
                $where['number|nick_name'] = ['like','%'.$this->get['keywords'].'%'];
            }
            $list  = db($this->tn)->field('*,FROM_UNIXTIME(birthday,"%Y-%m-%d") as birthday,FROM_UNIXTIME(register_time,"%Y-%m-%d %H:%i") as register_time,FROM_UNIXTIME(grade_end_time,"%Y-%m-%d") as grade_end_time,FROM_UNIXTIME(last_login_time,"%Y-%m-%d %H:%i:%s") as last_login_time')->where($where)->order('id', 'desc')->page($this->get['page'])->limit($this->get['limit'])->select();

            $area = db('area');
            foreach ($list as $k => $v) {

                $city = $area->where('id',$v['from_city'])->find();
                if($city){
                    $list[$k]['from_city'] = $city['name'];
                }else{
                    $list[$k]['from_city'] = '';
                }
                $list[$k]['zhiye'] = $v['zhiye'] == 0 ? '' : db('zhiye')->where('id',$v['zhiye'])->value('name');
            }
            $count = db($this->tn)->where($where)->count();
            $this->returnAPI('', 0, $list, ['count' => $count, 'limit' => $this->get['limit']]);
        }
        return $this->fetch();
    }

    public function edit($id = 0)
    {
        $model = model($this->tn);
        if ($this->post) {
            if ($id) {
                $model = $model->get($id);
                if (is_null($model)) {
                    $this->returnAPI('信息有误,请稍后重试');
                }
            }
            $result = $model->validate($this->tn)->allowField(true)->save($this->post);
            if ($result !== false) {
                $this->returnAPI('操作成功', 0);
            }
            $this->returnAPI($model->getError());
        }
        $model = $model->get($id);
        if (is_null($model)) {
            $data = $this->table_fields($this->tn);
        } else {
            $data = $model->getData();
        }
        return $this->fetch('', ['data' => $data]);
    }
}
